package com.jf.demo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.jivesoftware.smack.SmackAndroid;
import org.jivesoftware.smack.packet.Presence;
import org.json.JSONArray;
import org.json.JSONException;

import com.jf.map.MyOrderMap;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.sys.android.util.FinalUntil;
import com.sys.android.xmppmanager.XmppConnection;
import com.sys.android.xmppmanager.XmppConnectionListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

@ContentView(R.layout.mainmenu)
public class Mainmenu extends Activity {

	public long firstTime = 0;

	private int[] messImage = FinalUntil.messImage;

	private String menuName[] = { "我要发件", "我要收件", "我的运单", "常用地址", "周边服务",
			"我的消息" };

	// 主菜单要跳转的类
	private Class<?> menuClass[] = { MySendFile.class, MyOrder.class,
			MyAlreadyOrder.class, OftenAddress.class, NearbyServ.class,
			MyMessage.class };
	// 主菜单图标
	private int menuImage[] = { R.drawable.menu_fajian,
			R.drawable.menu_shoujian, R.drawable.menu_yundan,
			R.drawable.menu_address, R.drawable.menu_fuwu,
			R.drawable.menu_xinxi };

	private ArrayList<HashMap<String, Object>> remoteWindowItem;

	private SharedPreferences useShare;

	private ListView vncListView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);// xml视图加载的处理
		useShare = getSharedPreferences("userInfo", MODE_PRIVATE);
		String username = useShare.getString("username", "");
		String password = useShare.getString("password", "");
		try {
			SmackAndroid.init(Mainmenu.this);
			// XmppConnection.getConnection();
			XmppConnection.getConnection().login(username, password);
			// 连接服务器成功，更改在线状态
			Presence presence = new Presence(Presence.Type.available);
			XmppConnection.getConnection().sendPacket(presence);
			XmppConnectionListener conlistten = new XmppConnectionListener();
			XmppConnection.getConnection().addConnectionListener(conlistten);
		} catch (Exception e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// Toast.makeText(MainActivity.this,"网络连接失败",
			// Toast.LENGTH_LONG).show();
		}

		// setContentView(R.layout.mainmenu);
		/*--------------------菜单部分-----------------*/
		GridView gridview = (GridView) findViewById(R.id.gridView1);
		ArrayList<HashMap<String, Object>> meumList = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < 6; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("ItemImage", menuImage[i]);
			map.put("ItemText", menuName[i]);
			meumList.add(map);
		}
		SimpleAdapter saItem = new SimpleAdapter(this, meumList, // 数据源
				R.layout.mainmenuitem, // xml实现
				new String[] { "ItemImage", "ItemText" }, // 对应map的Key
				new int[] { R.id.ItemImage, R.id.ItemText }); // 对应R的Id

		// 添加Item到网格中
		gridview.setAdapter(saItem);
		// 添加点击事件
		gridview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				int index = arg2;// id是从0开始的，所以需要+1
				Intent intent = new Intent(Mainmenu.this, menuClass[index]);
				startActivityForResult(intent, 1);
				// Toast.makeText(getApplicationContext(), "你按下了选项："+index,
				// 0).show();
			}
		});
		/*--------------------动态部分-----------------*/
		vncListView = (ListView) findViewById(android.R.id.list);
		orerList();
	}

	public void clickPerson(View v) {
		Intent intent = new Intent();
		intent.setClass(Mainmenu.this, PersonalInfo.class);
		startActivity(intent);
	}

	public void orerList() {

		RequestParams params = new RequestParams();
		params.addQueryStringParameter("mobileUserId",
				useShare.getString("username", ""));

		HttpUtils http = new HttpUtils();
		http.send(HttpMethod.POST, FinalUntil.ServerAddress + "findMenuOrder",
				params, new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						// TODO Auto-generated method stub
						Log.i("Mainmenu", arg1);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						// arg0.result返回服务器结果
						Log.i("Mainmenu", arg0.result);
						try {
							// 生成动态数组，加入数据
							remoteWindowItem = new ArrayList<HashMap<String, Object>>();
							JSONArray jsonarr = new JSONArray(arg0.result);
							for (int i = 0; i < jsonarr.length(); i++) {
								String resulrContent = "";
								if ("3".equals(jsonarr.getJSONObject(i)
										.getString("states"))) {
									resulrContent = "成功受理,快递员：";
								}
								HashMap<String, Object> map = new HashMap<String, Object>();
								int imagm = jsonarr.getJSONObject(i).getInt(
										"brand");
								map.put("ItemImage", messImage[imagm]);// 图像资源的ID
								map.put("ItemWinName",
										resulrContent
												+ jsonarr.getJSONObject(i)
														.getString(
																"contendOrder"));
								map.put("ItemCloseWin",
										android.R.drawable.ic_menu_close_clear_cancel);
								map.put("states", jsonarr.getJSONObject(i)
										.getString("states"));
								map.put("mapX", jsonarr.getJSONObject(i)
										.getString("mapX"));
								map.put("mapY", jsonarr.getJSONObject(i)
										.getString("mapY"));
								map.put("courphone", jsonarr.getJSONObject(i)
										.getString("courphone"));
								map.put("releaseId", jsonarr.getJSONObject(i)
										.getString("id"));
								map.put("brand", jsonarr.getJSONObject(i)
										.getString("brand"));
								map.put("contendOrder",
										jsonarr.getJSONObject(i).getString(
												"contendOrder"));
								remoteWindowItem.add(map);
							}
							MainmenuList listItemAdapter = new MainmenuList(
									Mainmenu.this, remoteWindowItem, "操 作");

							vncListView.setAdapter(listItemAdapter);
							vncListView
									.setOnItemClickListener(new OnItemClickListener() {

										@Override
										public void onItemClick(
												AdapterView<?> arg0, View arg1,
												int arg2, long arg3) {

											dialogAlert(
													remoteWindowItem.get(arg2)
															.get("states")
															.toString(), arg2);

										}
									});
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			long secondTime = System.currentTimeMillis();
			if (secondTime - firstTime > 800) {// 如果两次按键时间间隔大于800毫秒，则不退出
				Toast.makeText(Mainmenu.this, "再按一次退出程序", Toast.LENGTH_SHORT)
						.show();
				firstTime = secondTime;// 更新firstTime
				return true;
			} else {
				System.exit(0);// 否则退出程序
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		orerList();
	}

	/**
	 * 订单操作菜单
	 */
	public void dialogAlert(String states, int args) {

		final String releaseId = remoteWindowItem.get(args).get("releaseId")
				.toString();

		if ("3".equals(states)) {
			final String courphone = remoteWindowItem.get(args)
					.get("courphone").toString();
			final Double mapX = Double.valueOf(remoteWindowItem.get(args)
					.get("mapX").toString());
			final Double mapY = Double.valueOf(remoteWindowItem.get(args)
					.get("mapY").toString());
			final String courName = remoteWindowItem.get(args)
					.get("contendOrder").toString();
			final int brandImag = Integer.valueOf(remoteWindowItem.get(args)
					.get("brand").toString());
			Dialog dialog = new AlertDialog.Builder(this).setTitle("订单操作")
					.setMessage("请在下列菜单中选择操作")
					.setPositiveButton("电话联系", new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							Intent intent = new Intent();
							intent.setAction("android.intent.action.CALL");
							intent.setData(Uri.parse("tel:" + courphone));
							startActivity(intent);
						}
					}).setNegativeButton("快递员位置", new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							Intent intent = new Intent();
							intent.putExtra("mapX", mapX);
							intent.putExtra("mapY", mapY);
							intent.putExtra("courName", courName);
							intent.putExtra("brandImag", brandImag);
							intent.setClass(Mainmenu.this, MyOrderMap.class);
							startActivity(intent);
						}
					}).setNeutralButton("消息沟通", new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							Intent intent = new Intent();
							intent.putExtra("sendcall", courphone);
							intent.putExtra("sendName", courName);
							intent.setClass(Mainmenu.this,
									com.jf.socketMess.MyMessage.class);
							startActivity(intent);
						}
					}).create();
			dialog.show();
		} else {
			Dialog dialog = new AlertDialog.Builder(this).setTitle("订单操作")
					.setMessage("撤单后两小时内不被服务")
					.setPositiveButton("撤单", new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							RequestParams params = new RequestParams();
							params.addQueryStringParameter("releaseId",
									releaseId);
							HttpUtils http = new HttpUtils();
							http.send(HttpMethod.POST, FinalUntil.ServerAddress
									+ "deleteRelease", params,
									new RequestCallBack<String>() {

										@Override
										public void onFailure(
												HttpException arg0, String arg1) {
											// TODO Auto-generated method stub
											Log.i("Mainmenu", arg1);
										}

										@Override
										public void onSuccess(
												ResponseInfo<String> arg0) {
											// arg0.result返回服务器结果
											orerList();
										}
									});
						}
					}).create();
			dialog.show();
		}
	}
}
